import { ref, onMounted, onBeforeUnmount } from "vue";
import axios from "axios";

export default function useRequest(url, autoLoad = true) {

    /* 创建cancel-token */
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();

    /* 定义loading,data,err */
    const loading = ref(false);
    const data = ref("null");
    const err = ref("null");

    /* 发起请求 */
    const ajax = () => {
        loading.value = true;

        axios
            .get(url, {
                cancelToken: source.token,
            })
            .then((result) => {
                console.log("ajax ok: result=", result);
                data.value = result;
                err.value = "null";
            })
            .catch((reason) => {
                console.log("ajax failed: reason=", reason);
                err.value = reason;
                data.value = "null";
            })
            .finally(() => (loading.value = false));
    }

    /* 取消请求 */
    const cancel = () => {
        // 取消请求（message 参数是可选的）
        if (loading.value) {
            source.cancel("请求已取消！");
        }
    }

    /* 组件一挂载就请求网络数据 */
    onMounted(() => autoLoad && ajax());

    /* 组件卸载前取消未竟的请求 */
    onBeforeUnmount(() => cancel());

    return { loading, data, err, ajax, cancel }
}